package com.hula.onion.book.server.spider.platforms.wenshangdai;

import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.LoginForm;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by work on 2018/2/1.
 */
@Component
public class WenShangDaiSpiderHelper {

    private static final Logger logger = LoggerFactory.getLogger(WenShangDaiSpiderHelper.class);

    public Map<String, Object> installRequestParams(LoginForm loginForm) {
        Map<String, Object> map = new HashMap<>(3);
        map.put("inpUser", loginForm.getUserName());
        map.put("inpPass", loginForm.getPassword());
        map.put("mm", "密码");
        map.put("bc", "1");
        map.put("act", "ok");
        map.put("button", "登陆");
        map.put("hfUrl", "http://www.wsloan.com/");
        return map;
    }

    /**
     * 解析账户余额
     *
     * @param html
     * @return
     */
    public CommonResponse parseAccountBalance(String html) {
        if (StringUtils.isEmpty(html)) {
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        }

        try {
            AccountInfo accountInfo = new AccountInfo();
            Document document = Jsoup.parse(html);
            Element amountElement = document.selectFirst("dl.totalAssets");
            String amount = amountElement.getAllElements().get(5).text();
            accountInfo.setAmount(new BigDecimal(amount));
            Element yIElement = document.selectFirst("p.yesterdayIncome");
            String yesterdayIntrest = yIElement.text();
            accountInfo.setYesterdayIntrest(new BigDecimal(yesterdayIntrest));
            Element tIElement = document.selectFirst("div.m_right2_lb");
            String totalIntrest = tIElement.getAllElements().get(15).text();
            accountInfo.setTotalIntrest(new BigDecimal(totalIntrest));
            return new CommonResponse(accountInfo);
        } catch (Exception e) {
            logger.error("[XiangShangJinFuSpiderHelper] parseAccountBalance fail!", e);
        }
        return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
    }
}
